package analysis;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.objdetect.CascadeClassifier;

import utils.ImageDeted;

//
// Classe che si occupa di rilevare il viso.
// 

public class FaceDet implements IDetection {

	CascadeClassifier faceDetector;
	MatOfRect faceDetections;
	Rect[] rect;

	int iTmp = 0;
	int nTmp = 0;
	int aTmp = 0;
	Mat tmp;

	public ImageDeted run(ImageDeted id) {

		id = extractFace(id, "lbpcascade_frontalface.xml");
		id.setSemaforo(-1);

		return id;

	}

	private ImageDeted extractFace(ImageDeted id, String filename) {

		faceDetector = new CascadeClassifier("././src/res/" + filename);
		faceDetections = new MatOfRect();

		faceDetector.detectMultiScale(id.getImage(), faceDetections, 1.1, 6, 0,
				new Size(150, 150), new Size());

		rect = faceDetections.toArray();

		for (int i = 0; i < rect.length; i++) {
			Core.rectangle(id.getImage(), new Point(rect[i].x, rect[i].y),
					new Point(rect[i].x + rect[i].width, rect[i].y
							+ rect[i].height), new Scalar(0, 255, 0));
		}

		if (rect.length > 0) {
			id.setVolti(rect);
			id.setFace(id.getImage().submat(rect[0]));
		} else {
			id.setVolti(null);
		}

		return id;
	}
}